<?php

	class PasteCommand implements ICommand
	{
		public function execute($event)
		{
			$source = $event->data["source"];
			$target = $event->data["target"];
			$move = $event->data["move"];
		
			$result = $this->copyr(ROOT.$source,ROOT.$target);
			
			if ($move == "true" && $result)
			{
				if (is_dir(ROOT.$source))
				{
					$this->removeDir(ROOT.$source);
				}
				elseif (is_file(ROOT.$source))
				{
					unlink(ROOT.$source);
				}
			}
			
			return $result;
		}
		
		/**
		* Remove a DIR
		*/
		function removeDir($dir) 
		{
			if(!$dh = opendir($dir)) return;
			
			while (false !== ($obj = readdir($dh))) 
			{
				if($obj=='.' || $obj=='..') continue;
				
				if (is_file($dir.'/'.$obj))
				{
					unlink($dir.'/'.$obj);
				}
				elseif (is_dir($dir.'/'.$obj))
				{
					$this->removeDir($dir.'/'.$obj);
				}
			}

			closedir($dh);
			
			rmdir($dir);
		}		
		
		/**
		 * Copy a file, or recursively copy a folder and its contents
		 *
		 * @author      Aidan Lister <aidan@php.net>
		 * @version     1.0.1
		 * @link        http://aidanlister.com/repos/v/function.copyr.php
		 * @param       string   $source    Source path
		 * @param       string   $dest      Destination path
		 * @return      bool     Returns TRUE on success, FALSE on failure
		 */
		function copyr($source, $dest)
		{
			// Check for symlinks
			if (is_link($source)) {
				return symlink(readlink($source), $dest);
			}

			// Simple copy for a file
			if (is_file($source)) {
				return copy($source, $dest);
			}

			// Make destination directory
			if (!is_dir($dest)) {
				mkdir($dest);
			}

			// Loop through the folder
			$dir = dir($source);
			while (false !== $entry = $dir->read()) {
				// Skip pointers
				if ($entry == '.' || $entry == '..') {
					continue;
				}

				// Deep copy directories
				copyr("$source/$entry", "$dest/$entry");
			}

			// Clean up
			$dir->close();
			return true;
		}
	}